package common

import (
	"bytes"
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/tealeg/xlsx"
)

//文件下载
func fileDownload(c *gin.Context) {
	name := "test.xlsx"

	xFile := xlsx.NewFile()
	sheet, err := xFile.AddSheet("test")
	if err != nil {
		panic(err)
	}
	header := []string{"姓名", "性别", "年龄"}
	r := sheet.AddRow()
	var ce *xlsx.Cell
	for _, v := range header {
		ce = r.AddCell()
		ce.Value = v
	}
	for i := 1; i < 5; i++ {
		r = sheet.AddRow()
		ce = r.AddCell()
		ce.Value = "张三"
		ce = r.AddCell()
		ce.Value = "男"
		ce = r.AddCell()
		ce.Value = fmt.Sprintf("%d", 23)
	}
	//将数据存入buff中
	var buff bytes.Buffer
	if err = xFile.Write(&buff); err != nil {
		panic(err)
	}

	// 设置返回头并返回数据
	contentType := "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"

	fileContentDisposition := "attachment;filename=\"" + name + "\""
	c.Header("Content-Type", contentType) // 这里是压缩文件类型 .zip
	c.Header("Content-Disposition", fileContentDisposition)
	c.Data(http.StatusOK, contentType, buff.Bytes())

}
